// Global namespace
var MasterStroke = MasterStroke || {};
MasterStroke.ViewModels = MasterStroke.ViewModels || {};

define
(    
    ["lib/knockout",
     "Common/BufferLoader"],
    function(ko,
                 BufferLoader)
    {
        MasterStroke.ViewModels.AnimationViewModel = function(frames, closeCommand, frameRate, soundUrl)
        {
            this.selectedFrame = ko.observable(frames && frames.length ? frames[0] : null);
            this.replayVisible = ko.observable(false);
            this.closeCommand = closeCommand;
            frameRate = frameRate || 60;
            soundUrl = soundUrl ? ("/stream/" + soundUrl) : null;
            var _that = this;
            var _frames = frames;
            var _timer;
            var _frameIndex;
            var _soundSource;

            this.start = function()
            {
                _frameIndex = 0;
                var interval = 1000 / frameRate;
                _that.replayVisible(false);
                
                if (soundUrl)
                {
                    window.AudioContext = window.AudioContext || window.webkitAudioContext;
                    context = new AudioContext();
                    bufferLoader = new BufferLoader(context,
                                                                     [soundUrl],
                                                                     function(bufferList)
                                                                     {
                                                                        _soundSource = context.createBufferSource();
                                                                        _soundSource.buffer = bufferList[0];
                                                                        _soundSource.connect(context.destination);
                                                                        _soundSource.start(0);
                                                                        _timer = window.setInterval(play, interval);
                                                                     });
                    bufferLoader.load();
                }
                else
                {
                    _timer = window.setInterval(play, interval);
                }
            };

            function play()
            {
                if (_frameIndex === _frames.length - 1)
                {
                    _that.replayVisible(true);
                    window.clearInterval(_timer);

                    if (_soundSource)
                    {
                        _soundSource.stop(0);
                    }                    
                }

                _that.selectedFrame(_frames[_frameIndex++]);
            }
        };

        return MasterStroke.ViewModels.AnimationViewModel;
    }
);